package com.qf.dao.impl;

import com.qf.dao.UserDao;

import com.qf.dao.UserDao;
import com.qf.entity.User;
import com.qf.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.PrimitiveIterator;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr = new QueryRunner(JdbcUtils.ds);

    @Override
    public User findOneByUser(String phone ) {
        try {
            User user = qr.query("select * from user where phone=?", new BeanHandler<>(User.class), phone);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public int add(User user) {
        String sql = "insert into t_user values (0,?,?,null,null)";
        try {
            return qr.update(sql,user.getPhone(),user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User login(User user) {
        String sql = "select * from t_user where phone=? and password= ?";
        try {
            User user1 = qr.query(sql,new BeanHandler<>(User.class),user.getPhone(), user.getPassword());
            return user1;
        }catch(SQLException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User findOne(Integer id) {
        String sql = "select * from t_user where id = ?";
        try {
            return qr.query(sql,new BeanHandler<>(User.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int update(User user) {
        String sql = "update t_user set phone = ?,password=?,id_num=?,username=? where id = ?";
        try {
            return qr.update(sql,user.getPhone(),user.getPassword(),user.getId_num(),user.getUsername(),user.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
